<script setup>
// watch
// 0. 语法 watch(数据源, handler, option)
// 1. 监视基本数据类型
// 2. 监视多个基本数据类型
// 3. 监视复杂数据类型
//  - vue3默认开启深度监听, 层级多深都能监听到,跟vue2不一样, 只能监视第一层, deep:true才能深度监听
//  - 要么监听ref.value, 要么监听ref + {deep:true} 
// 4. 监听复杂数据类型的属性

import { reactive, ref, watch } from 'vue';

//监视基本数据类型
const num = ref(0)
const add = () => num.value++
watch(num, (newVal, oldVal) => console.log(newVal, oldVal))

//监视多个基本数据类型
const name = ref('张三'),
  age = ref(18)

const changeNameAndAge = () => {
  name.value = '李四',
    age.value = '25'
}
// watch([name, age], (newValues, oldValues) => console.log(newValues, oldValues))
watch([name, age], ([newName, newAge]) => console.log(newName, newAge))

// 监视复杂数据类型
// 1. 监听reactive定义的复杂数据类型
// const info = reactive({
//   name: '王二',
//   famaliy: {
//     mom: '韩梅梅',
//     father: '王大海'
//   }
// })
// const changeInfo = () => {
//   info.name = '王八'
//   info.famaliy.mom = "韩小明"
//   info.famaliy.father = "王九九"
// }
// watch(info, (newVal) => console.log(newVal.name, newVal.famaliy.mom, newVal.famaliy.father))

// 2. 监听ref定义的复杂数据类型
const info = ref({
  name: '王二',
  famaliy: {
    mom: '韩梅梅',
    father: '王大海'
  }
})
// const changeInfo = () => {
//   // info.value.name = '王八'
//   info.value.famaliy.mom = "韩小明"
//   info.value.famaliy.father = "王九九"
// }
// watch(info.value, (newVal) => console.log(newVal.name, newVal.famaliy.mom, newVal.famaliy.father))
// watch(info, (newVal) => console.log(newVal.name, newVal.famaliy.mom, newVal.famaliy.father), { deep: true })


// 监听复杂数据类型的属性
const changeMom = () => (info.value.famaliy.mom = '王美美')
watch(
  () => info.value.famaliy.mom,
  (newVal) => console.log(newVal)
)
</script>
<template>
  <div>
    <p>当前的数字是: {{ num }}</p>
    <button @click="add">数字+1</button>

    <hr />
    <p>当前的姓名是: {{ name }} </p>
    <p>当前的年龄是: {{ age }}</p>
    <button @click="changeNameAndAge">更改年龄和姓名</button>

    <hr />
    <p>当前的姓名是: {{ info.name }} </p>
    <p>家庭成员是: {{ info.famaliy }}</p>
    <button @click="changeInfo">更改家庭信息</button>
    <button @click="changeMom">更改妈妈名字</button>

  </div>
</template>

